﻿<?php
//CHANGE INDEX __construct
if (!defined('BASEPATH'))
   exit('No direct script access allowed');
session_start();
ini_set("session.cookie_lifetime","14400");
class Contest extends MX_Controller {

   private $module = 'contest';
   private $table = 'contest';

   function __construct() {
      parent::__construct();
      $this->load->model($this->module . '_model', 'model');
      if ($this->uri->segment(1) == 'admincp') {
         if ($this->uri->segment(2) != 'login') {
            if (!$this->session->userdata('userInfo')) {
               header('Location: ' . PATH_URL . 'admincp/login');
               return false;
            }
         }
         $this->template->set_template('admin');
         $this->template->write('title', 'Admin Control Panel');
      } else {
         if(!isset($_SESSION['profile'])){
           require 'application/libraries/facebook.php';
           $facebook = new Facebook(array('appId'  => FB_APP_ID, 'secret' => FB_SECRET));
           $signed_request = $facebook->getSignedRequest();
           $user_profile = $facebook->api('/me');
          
           $_SESSION['profile'] =  $user_profile;
           $_SESSION['fb_id']= $signed_request['user_id'];
           } 
      }
   }

   /* ------------------------------------ Admin Control Panel ------------------------------------ */

   public function admincp_index() {
      $default_func = 'created';
      $default_sort = 'DESC';

      $data = array(
          'module' => $this->module,
          'default_func' => $default_func,
          'default_sort' => $default_sort,
          'weeks' => $this->model->get_list_weeks()
      );
       
      $this->template->write_view('content', 'BACKEND/index', $data);
      $this->template->render();
   }


   public function admincp_save() {
      //Upload Image
      $fileName = array('image' => '');
            if ($_FILES) {
                foreach ($fileName as $k => $v) {
                    if (isset($_FILES['fileAdmincp']['error'][$k])) {
                        $typeFileImage = strtolower(substr($_FILES['fileAdmincp']['type'][$k], 0, 5));
                        if ($typeFileImage == 'image' || $typeFileImage == 'video') {
                            $tmp_name[$k] = $_FILES['fileAdmincp']["tmp_name"][$k];
                            $file_name[$k] = $_FILES['fileAdmincp']['name'][$k];
                            $ext = strtolower(substr($file_name[$k], -4, 4));
                            if ($ext == 'jpeg') {
                                $fileName[$k] = time() . '_' . SEO(substr($file_name[$k], 0, -5)) . '.jpg';
                            } else {
                                $fileName[$k] = time() . '_' . SEO(substr($file_name[$k], 0, -4)) . $ext;
                            }
                        } else {
                            print 'Only upload Image.';
                            exit;
                        }
                    }
                }
            }
      //End Upload Image

      if ($this->model->saveManagement($fileName)) {
         //Upload Image
         if ($_FILES) {
            if (isset($_FILES['fileAdmincp']['error'])) {
                 foreach ($fileName as $k => $v) {
                   $upload_path = BASEFOLDER . 'static/uploads/contest/';
                     move_uploaded_file($tmp_name[$k], $upload_path . $fileName[$k]);
                 }
            }
         }
         //End Upload Image
         print 'success';
         exit;
      }
   }

   public function admincp_update($id = 0) {
      $result[0] = array();
      if ($id != 0) {
         $result = $this->model->getDetailManagement($id);
      }
      $data = array(
          'result' => $result[0],
          'module' => $this->module,
          'id' => $id,
          'users' => $this->model->list_users(),
          'province' => $this->model->get_province(),
      );
      $this->template->write_view('content', 'BACKEND/ajax_editContent', $data);
      $this->template->render();
   }

  
   public function admincp_delete() {
        if ($this->input->post('id')) {
            $id = $this->input->post('id');
            $result = $this->model->getDetailManagement($id);
            $this->db->where('id', $id);
            if ($this->db->delete(PREFIX . $this->table)) {
                return true;
            }
        }
    }


   public function admincp_ajaxLoadContent() {
	
      $this->load->library('AdminPagination');
      $config['total_rows'] = $this->model->getTotalsearchContent();
      $config['per_page'] = $this->input->post('per_page');
      $config['num_links'] = 3;
      $config['func_ajax'] = 'searchContent';
      $config['start'] = $this->input->post('start');
      $this->adminpagination->initialize($config);

      $result = $this->model->getsearchContent($config['per_page'], $this->input->post('start'));
    
      $data = array(
          'result' => $result,
          'per_page' => $this->input->post('per_page'),
          'start' => $this->input->post('start'),
          'module' => $this->module
      );
      $this->session->set_userdata('start', $this->input->post('start'));
      $this->load->view('BACKEND/ajax_loadContent', $data);
   }

   public function admincp_ajaxUpdateWinnerStatus() {
      if ($this->input->post('winner') == 0) {
         $winner = 1;
      } else {
         $winner = 0;
      }
      $data = array(
          'is_winner' => $winner
      );
      $this->db->where('id', $this->input->post('id'));
      $this->db->update(PREFIX . $this->table, $data);

      $update = array(
          'is_winner' => $winner,
          'id' => $this->input->post('id'),
          'module' => $this->module
      );
      $this->load->view('BACKEND/ajax_updateWinnerStatus', $update);
   }
   public function admincp_ajaxUpdateWinnerWeeks() {
      if ($this->input->post('winner_week') == 0) {
         $winner_week = 1;
      } else {
         $winner_week = 0;
      }
      $data = array(
          'winner_week' => $winner_week
      );
      $this->db->where('id', $this->input->post('id'));
      $this->db->update(PREFIX . $this->table, $data);

      $update = array(
          'winner_week' => $winner_week,
          'id' => $this->input->post('id'),
          'module' => $this->module
      );
      $this->load->view('BACKEND/ajax_updateWinnerWeeks', $update);
   }

   public function admincp_ajaxUpdateStatus() {
      if ($this->input->post('status') == 0) {
         $status = 1;
      } else {
         $status = 0;
      }
      $data = array(
          'status' => $status,
          'modify' =>date('Y-m-d H:i:s', time()),
      );
      $this->db->where('id', $this->input->post('id'));
      $this->db->update(PREFIX . $this->table, $data);

      $update = array(
          'status' => $status,
          'id' => $this->input->post('id'),
          'module' => $this->module
      );
      $this->load->view('BACKEND/ajax_updateStatus', $update);
   }

   public function admincp_ajaxUpdateNoibat() {
      if ($this->input->post('status') == 0) {
         $status = 1;
      } else {
         $status = 0;
      }
      $data = array(
          'noibat' => $status
      );
      $this->db->where('id', $this->input->post('id'));
      $this->db->update(PREFIX . $this->table, $data);

      $update = array(
          'status' => $status,
          'id' => $this->input->post('id'),
          'module' => $this->module
      );
      $this->load->view('BACKEND/ajax_updateNoibat', $update);
   }
   public function admincp_export() {
        $data = array(
            'module' => $this->module
        );
        $this->template->write_view('content', 'BACKEND/ajax_export',$data);
        $this->template->render();
    }
     public function admincp_export_excel() {
        ini_set('memory_limit','300M');
        $date_start = $this->input->post("datestart");
        $date_end = $this->input->post("dateend");
        $report = $this->model->getContentUser($date_start,$date_end);
    
        $html_top = '
        <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
        Zhtml xmlns="http://www.w3.org/1999/xhtml">
        <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        </head>
        <body>
        <table width="1191" cellpadding="0" cellspacing="0" border="1" align="right" style="font-size:12px;">';
        $n=1;
        $html = '';
        $html_bot = '
        </table>
        </body>
        </html>';
        $gender ;
        $filename ='export_contest';
        $html .='
            <tr height="50">
            <td height="20" align="right">'.'Thứ Tự'.'</td>
            <td>'.'Tên'.'</td>
            <td>'.'Bình Chọn'.'</td>
            <td>'.'Phone	'.'</td>
            <td>'.'Tên Facebook'.'</td>
            <td>'.'Email'.'</td>
            <td>'.'Nội Dung'.'</td>
            <td>'.'fbid'.'</td>
            <td>'.'Tham Gia	'.'</td>
            </tr>';
            
        foreach ($report as $item) {
            $like = $this->model->getCountLike($date_start,$date_end,$item->id);
            $html .='
            <tr height="100">
            <td height="20" align="right">'.$n.'</td>
            <td height="100">'.$item->fullname.'</td>
            <td height="100">'.$like.'</td>
            <td height="100"  align="center">'.$item->phone.'</td>
            <td height="100">'.$item->username.'</td>
            <td height="100">'.$item->email.'</td>
            <td height="200">'.$item->content.'</td>
            <td height="100">'.$item->fb_id.'</td>
            <td height="100">'.getVNDateTime($item->created,true).'</td>
            </tr>';
            $n++;
        }
        header("Content-type: application/x-www-form-urlencoded\r\n" );
        header('Content-Disposition: attachment; filename="'.$filename.'.xls"');
        echo $html_top.$html.$html_bot;
    }
   /* ------------------------------------ End Admin Control Panel -------------------------------- */
    function OpenId($type = '')
    {
        $data['type'] = $type;
        $this->load->view('FRONTEND/OpenId', $data);
    }
    function LoginOpenId($type = 'google') {
        $info = get_attr_profile_openid($type);
        if (!empty($info['email'])) {
            $username = explode('@', $info['email']);
            //LOGIN SUCCESS			
            $USER = $this->model->get_profile($info['id']);
            $this->session->set_userdata('FB', $info);
            if (empty($USER)) {
                $data = array(
                    'type' => 1,
                    'fb_id' => $info['id'],
                    'username' => $username[0],
                    'email' => $info['email'],
                    'fullname' => $info['full_name'],
                    'randomkey' => _token(),
                    'created' => date('Y-m-d H:i:s')
                );
                $this->db->insert('cli_user', $data);
            } else {
                $data['fb_id'] = $info['id'];
                $this->db->where('id', $USER->id)->update('cli_user', $data);
            }
            $USER =  $this->model->get_profile($info['id']);
            $this->session->set_userdata('user_id', $USER->id);
            $this->session->set_userdata('fb_id', $info['id']);
            $json['st'] = 'SUCCESS';
            $json['information'] = (empty($USER->cmnd)) ? 'FALSE' : 'TRUE';
            print_r(json_encode($json));
        }
    }
   
  function the_le() {
        $this->template->write_view('content', 'FRONTEND/rule');
        $this->template->render(); 
   
  }
  function tham_gia() {
        $this->template->write_view('content', 'FRONTEND/thamgia');
        $this->template->render(); 
   
  }
 
  function upload_photo() {
        $this->template->write_view('content', 'FRONTEND/photo');
        $this->template->render(); 
   
  }
 
  
  function thu_vien() {
        $weeks = $this->model->get_list_weeks();
        $this->load->library('MyPagination');
        $pageNum= (int)$this->input->get('p');
        $order=  $this->input->get('o');
       	$pageSize= 6;
		$totalRows= $this->model->get_list_contest(-1,-1,$order);
		$pagination= pagination($totalRows, $pageNum, $pageSize, 6);
		if($pageNum == '') $pageNum= 1;
		$startRow = ($pageNum-1) * $pageSize;		
	    $result=$this->model->get_list_contest($pageSize, $startRow,$order);
      

		$data= array(
			'result' => $result,
			'pagination' => $pagination,
		);
        $this->template->write_view('content', 'FRONTEND/thuvien',$data);
        $this->template->render(); 
   
  }
 
  function thu_vien_chitiet($id)
  {
    $u=$_SESSION['profile'];
    $user_data = $this->model->get_user($u['id']);
    $contest_id = $id;
    $contest= $this->model->getContestDetail($contest_id);
    $comments= $this->model->get_comments($contest_id);
    if($contest->type == 3){
        $image = $this->model->get_contest_image($contest_id);
        $data= array(
            'contest' => $contest,
            'comments' =>$comments,
            'user_data'=>$user_data,
            'image' =>$image
        );
    }else
    {
        $data= array(
            'contest' => $contest,
            'comments' =>$comments,
            'user_data'=>$user_data
        );
    }
  
    $this->template->write_view('content', 'FRONTEND/thuvien_detail',$data);
    $this->template->render();    
  } 
   
   
   
  
   
    
   
  
   function ajax_comment_contest()
   {
      $content = $this->input->get_post('comment');
      $contest_id = $this->input->post("contest_id");
      $u=$_SESSION['profile'];
      $user_data = $this->model->get_user($u['id']);
      $data = array(
            'content' => $content,
            'user_id' =>$user_data[0]->id,
            'contest_id'=>$contest_id,
            'ip' => getIP(),
            'created' => date('Y-m-d H:i:s', time()),
            'status' => 1
        );
        if ($this->db->insert('`cli_contest_comment', $data)) {
             $contest = $this->model->getContestDetail($contest_id);
             $count_comment = $contest->comment + 1;
             $this->model->incre_comment($count_comment,$contest_id);
             $comments= $this->model->get_comments($contest_id);
             $data = array(
                'comments' => $comments
            
                );  
            $this->load->view('FRONTEND/ajax_comment', $data);
             
        }else
        {
            echo 0;
            exit();	
        }
   }
   public function insert_comment()
   {
         $content = $this->input->get_post('comment');
         $contest_id = $this->input->post("id");
      	 $u=$_SESSION['profile'];
         $user_data = $this->model->get_user($u['id']);
         $data = array(
            'content' => $content,
            'user_id' =>$user_data[0]->id,
            'contest_id'=>$contest_id,
            'ip' => getIP(),
            'created' => date('Y-m-d H:i:s', time()),
            'status' => 1
        );
       	header_xml();
        if ($this->db->insert('`cli_contest_comment', $data)) {
             $contest = $this->model->getContestDetail($contest_id);
             $count_comment = $contest->comment + 1;
             $this->model->incre_comment($count_comment,$contest_id);
             $comments= $this->model->get_comments($contest_id);
                if (!empty($comments)) {
                    
                    foreach($comments as $dt)
                    {
                        echo '<item>';
                            echo '<user>' . "<![CDATA[" . $dt->username . "]]>" . '</user>';
                            echo '<content>' . "<![CDATA[" . $dt->content . "]]>" . '</content>';
                            echo '<date>' . "<![CDATA[" . getVNDateTime($dt->created) . "]]>" . '</date>';
                         echo '</item>';
                     }
                } 
       
             
        }else
        {
            	
        }
        footer_xml();
        
   }
    function ajax_like_contest()
    {
         $contest_id = $this->input->post("contest_id");
      	 $u=$_SESSION['profile'];
         $user_data = $this->model->get_user($u['id']);
         
         $check_like = $this->model->is_like($user_data[0]->id,$contest_id);
         if($check_like > 0)
         {
            echo 1;
            exit();
         }
         $check_like_ip = $this->model->is_like_ip(getIP(),$contest_id);
         if($check_like_ip > 5)
         {
             echo 1;
             exit();
         }
         $data = array(
            'like' => 1,
            'user_id' =>$user_data[0]->id,
            'fb_id'=>$u['id'],  
            'contest_id'=>$contest_id,
            'ip' => getIP(),
            'created' => date('Y-m-d H:i:s', time()),
            'status' => 1
        );
        if ($this->db->insert('`cli_contest_like', $data)) {
             $contest = $this->model->getContestDetail($contest_id);
             $count_like = $contest->like + 1;
             $this->model->update_like($count_like,$contest_id);
             echo 2;
             exit();
        }else
        {
             echo 1;
             exit();
        }
        
    } 
  
   function upload(){
	 $current_user = $this->session->userdata('fb_id');

        if ($current_user) { // Check if user avaiable
            //Create user folder to store avatar
            $folder_avatar = DIR_UPLOAD_CONTEST;

            $have_folder = false;
            if (!is_dir($folder_avatar)) {
                $is_created = mkdir($folder_avatar, 0777);
                if ($is_created) {
                    $have_folder = true;
                }
            } else {
                $have_folder = true;
            }

            //Upload avatar
            if ($have_folder) {
                $avatar_size = array(
                    'small' => 25,
                    'medium' => 50,
                    'default' => 100
                );

                //Get upload file info
                $temp_file = $_FILES['avatar']['tmp_name'];
                $filename = uniqid(rand(1000000, 10000000));
                $ext = '.jpg';
                $file_path = $folder_avatar . $filename . $ext;

                //Unlink old file
                if (is_file($file_path)) {
                    unlink($file_path);
                    foreach ($avatar_size as $size) {
                        $file_thumb = $folder_avatar . $filename . '_' . $size . $ext;
                        if (is_file($file_thumb)) {
                            unlink($file_thumb);
                        }
                    }
                }

                move_uploaded_file($temp_file, $file_path);

                $default_thumb = '';
                foreach ($avatar_size as $key => $size) {
                    $file_thumb = $folder_avatar . $filename . '_' . $size . 'x' . $size . $ext;

                    if ($key == 'default') {
                        $default_thumb = $file_thumb;
                    }
                }

                print $filename . $ext;
            }
        }
	}
  
   
   public function upload_wall()
   {
     $fb_id = $_SESSION['fb_id'];
     $result= $this->model->get_user($fb_id);
     require 'application/libraries/facebook.php';
     $facebook = new Facebook(array('appId'  => FB_APP_ID, 'secret' => FB_SECRET));
     $user_id = $facebook->getUser();
     $signed_request = $facebook->getSignedRequest();
     $facebook->api('me/feed/', 'POST', array(
        'message' => 'Bạn '.$result[0]->fullname.' thân mến, bạn đã tham gia thành công chương trình "Vì người phụ nữ thân yêu". Davita Bone tin rằng người phụ nữ ấy sẽ rất hạnh phúc khi biết rằng bạn yêu thương và dành tình cảm cho họ nhiều như thế nào. Chúc bạn may mắn đạt giải thưởng của chương trình.',
        'name' => 'Vì người phụ nữ thân yêu.',
        'description' => 'Chia sẻ cách bày tỏ tình cảm với người phụ nữ bạn yêu thương để có cơ hội nhận ngay Ipad Air, Nokia Lumia 925 cùng nhiều giải thưởng hấp dẫn khác.',
        'caption' => 'Vì người phụ nữ thân yêu.',
        'picture' => PATH_URL.'static/images/share_facebook_end.png',
        'link' => 'https://apps.facebook.com/davitabonevn'
    ));
   }
   
   


   
    public function upload_images_from_link() {
            $url= $this->input->get_post("linkimg");
    
            $tmp = explode("/",$url);
        	$file = $tmp[count($tmp) - 1];
            $file = str_replace("%","-",$file);
            
        	//echo $url."<br/>";
        	if($file)
        	{
        		
        			$h = @fopen("$url","rb");
        			$content = '';
        			if($h)
        			{
        				while(!feof($h))
        				{
        					$buffer = fgets($h, 1024);
        					$content .= $buffer;
        				}
        				fclose($h);
        			}
        			$f = fopen(BASE_UPLOAD.$file,'w');
        			fwrite($f,$content);
        			fclose($f);
        			$ff = fopen(BASE_UPLOAD.$file,'w');
        			fwrite($ff,$content);
        			fclose($ff);
                    header_xml();
                        echo '<link>'.PATH_IMAGE.'contest_tmp/' .$file.'</link>';
                    footer_xml();
        	
        	}
        	else
        	{
        		 header_xml();
                        echo '<link>edf</link>';
                 footer_xml();
        	}
                    
        }
		

}